package registe_router_handle

import (
	"github.com/kataras/iris/v12"
	"goServer/models"
)

// return json model part
type Company struct {
	/*
		CompanyName  string `gorm:"type:varchar(20);not null;"`
		Business     string `gorm:"type:varchar(20);not null;"`
		RegCapital   string `gorm:"type:varchar(10);not null;"`
		Location     string `gorm:"type:varchar(20);not null;"`
		Region       string `gorm:"type:varchar(20);not null;"`
		LogoPath     string `gorm:"type:varchar(255);not null;"`
		Scale        string `gorm:"type:varchar(10);not null;"`
		Introduction string `gorm:"type:varchar(512);not null;"`
		Target       string `gorm:"type:varchar(20);not null;"`
		WorkPlace    string `gorm:"type:varchar(20);not null;"`
		ReqPosition  string `gorm:"type:varchar(100);not null;"`

		And rewrite the json model
	*/
	CompanyName  string `json:"company_name"`
	Business     string `json:"business"`
	RegCapital   string `json:"reg_capital"`
	Location     string `json:"location"`
	Region       string `json:"region"`
	LogoPath     string `json:"logo_path"`
	BkPath       string `json:"bk_path"`
	Scale        string `json:"scale"`
	Introduction string `json:"introduction"`
	Target       string `json:"target"`
	WorkPlace    string `json:"work_place"`
	ReqPosition  string `json:"req_position"`
	Telephone    string `json:"telephone"`
}

type CompanyInfo struct {
	CompanyInfo []Company `json:"company_info"`
}

// init part
func Init_CompanyInfo() {
	// GET localhost:8080/companyinfo?keyword=xxx
	// 给定关键词，返回所有包含关键词的宣讲会
	RouterHandles = append(RouterHandles, RouterHandle{
		Method: "GET",
		Router: "/companyinfo",
		Handler: func(ctx iris.Context) {
			keyword := ctx.URLParam("keyword")

			res := companiesFindAll(keyword)

			ctx.ContentType("application/json")
			ctx.JSON(res)
		},
	})
}

// deal data part (return json model)
func companiesFindAll(keyword string) CompanyInfo {
	// 放回一个CompanyInfo，包含所有名字包含keyword的Company，如果keyword为空，则返回所有Company

	// get db
	db, err := models.GetDBOnly()
	if err != nil {
		panic(err)
	}

	// get all companies：如果keyword为空，则返回所有Company，否则返回名字包含keyword的Company，Company中有来自models.Companies的数据
	var companyinfo CompanyInfo
	if keyword == "" {
		db.Raw("SELECT * FROM companies", "%"+keyword+"%").Scan(&companyinfo.CompanyInfo)
	} else {
		db.Raw("SELECT * FROM companies WHERE company_name LIKE ?", "%"+keyword+"%").Scan(&companyinfo.CompanyInfo)
	}

	return companyinfo
}
